import Vue from 'vue'
import VueRouter from 'vue-router'
import Cookies from 'js-cookie';
import {getUrlParams, redirectLogin} from "@/util";
import {checkTicket} from "@/api";

Vue.use(VueRouter)

// 定义路由规则数组
const routes = [
    {
        path: '/', component: () => import('@/views/Home.vue')
    }
]

// 创建路由对象
const router = new VueRouter({
    // 路由规则
    routes,
    mode: 'history'
})


// 路由守卫
router.beforeEach(async (to, from, next) => {
    let token = Cookies.get('token')
    let ticket = getUrlParams(location.href)['ticket'];

    // token 不存在, ticket 也不存在, 跳转门户登录页
    if (!token && !ticket) {
        redirectLogin();
    }

    // token 不存在, ticket 存在, 请求后端校验ticket
    if (ticket && ticket !== '') {
        await checkTicket(ticket).then(res => {
            // ticket 无效, 跳转门户登录页
            if (!res.data || res.data === '') {
                redirectLogin();
            }

            // 设置 token, 更新 token
            Cookies.set('token', res.data)
        });
    }

    // token 不存在跳转到门户登录页
    if (!token) {
        redirectLogin();
    }

    next();
});

// 导出定义好的路由规则
export default router


